<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Exception;//事务处理

class Cosale 
{
    public function __construct(Request $request){
        $this->getChildIDdata = [];
        $this->data = $request->param();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
    }

    /**
	    总信用额度 : credit = credit4order+credit4admin 
		订单信用额度 : credit4order,是每个订单完成后添加
		credit4admin : credit4admin = sum(co_credit4admin.point)有权限的管理员手动加的
	**/

    function list()
    {	
    	// 年月日
    	$timeDay = $this->getTimeDay();

    	// sale.receive_at>0 and sale.paid >= sale.pay
        $sql = "select * from nt_sale where paid >= pay and receive_at > 0";
        $sale_OK = Db::query($sql);



        // dump($sale_OK);die;
        foreach ($sale_OK as $k => $v) {
        	$coSaleWhere = [
        						'co_id'=>$v['co_id'],
        						'branch_id'=>$v['co_branch_id'],
        					];
        	$coSaleMonthWhere = ['co_id'=>$v['co_id'],'branch_id'=>$v['co_branch_id'],'sale_year'=>$timeDay['year'],'sale_month'=>$timeDay['month']];
        	// 获取更新前的数据
        	$oldco_saleData = Db::name('co_sale')->where($coSaleWhere)->find();
        	$pay_days   = $oldco_saleData ? $oldco_saleData['pay_days'] : 0;
        	$sale_qty   = $oldco_saleData ? $oldco_saleData['sale_qty'] +1: 0;
        	$profit 	= $oldco_saleData ? $oldco_saleData['profit'] : 0;
        	$sale_total = $oldco_saleData ? $oldco_saleData['sale_total'] : 0;

        	$coSaleData['pay_days']    = $this->getPayDays($v['id'],$pay_days,$sale_qty,$v['create_at']); 	//	平均订单付款完成天数
        	$coSaleData['sale_qty']    = $sale_qty; 										//	所有订单数量合计

        	$coSaleData['sale_last_id']= $v['id']; 			//	最后的订单ID
        	$coSaleData['sale_last_at']= $v['create_at']; 	//	最后的订单时间

        	$coSaleData['profit']      = $profit + $v['profit']; 		//	所有销售单毛利润
        	$coSaleData['sale_total']  = $sale_total + $v['pay']; 		//	所有的金额合计
        	$coSaleData['update_at']   = time(); 		

        	// 如果当天是1号 则更新 订单信用额度：credit4order
        	if($timeDay['today'] == 1){
        		$coSaleData['credit4admin'] = $this->countCredit4admin($v['co_id'],$v['co_branch_id']);
        		$coSaleData['credit4order'] = $this->countCredit4order($v['co_id'],$v['co_branch_id'],$timeDay);
        		$coSaleData['credit'] 		= $coSaleData['credit4admin'] + $coSaleData['credit4order'];

        		$saleMonthData = $this->getsaleMonthData($coSaleWhere,$coSaleMonthWhere,'1,3');
	        	// 当月之前三个月数据
	        	$coSaleData['sale_total_3m'] 	 = $saleMonthData ? $saleMonthData['total'] : 0; 			//	3个月内的金额合计(应付)
	        	$coSaleData['sale_qty_3m'] 	 	 = $saleMonthData ? $saleMonthData['sale_qty'] : 0; 		//	3个月内的订单数量合计
	        	$coSaleData['trouble_3m'] 	 	 = $saleMonthData ? $saleMonthData['trouble'] : 0; 			//	3个月内的故障订单数量
	        	$coSaleData['trouble_value_3m']  = $saleMonthData ? $saleMonthData['trouble_value'] : 0; 	//	3个月内的故障订单金额
	        	$coSaleData['profit_3m'] 		 = $saleMonthData ? $saleMonthData['profit'] : 0; 			//	3个月内的毛利润


        		$saleMonthData = $this->getsaleMonthData($coSaleWhere,$coSaleMonthWhere,'1,12');
	        	// 当月之前12个月的数据
	        	$coSaleData['sale_total_1y'] 	 = $saleMonthData ? $saleMonthData['total'] : 0; 			//	1年内的金额合计（应付）
	        	$coSaleData['sale_qty_1y'] 		 = $saleMonthData ? $saleMonthData['sale_qty'] : 0; 			//	1年内的订单数量合计
	        	$coSaleData['trouble_1y'] 		 = $saleMonthData ? $saleMonthData['trouble'] : 0; 			//	1年内的故障订单数量
	        	$coSaleData['trouble_value_1y']  = $saleMonthData ? $saleMonthData['trouble_value'] : 0; 	//	1年内的故障订单金额
	        	$coSaleData['profit_1y'] 		 = $saleMonthData ? $saleMonthData['profit'] : 0; 			//	1年内的毛利润
        	}
        	//存在更新， 不存在添加
        	if($oldco_saleData){
        		$res = updateData('co_sale',$coSaleWhere,$coSaleData);
        	}else{
        		$res = insertData('co_sale',$coSaleData);
        	}
        	// 更新 月记录表
        	if($res){
                // 获取月数据， 并更新当月数据
                $res1 = $this->updateDataSaleMonth($coSaleMonthWhere,'month',$v);

                // 获取年数据，并更新当前年份数据
                $coSaleMonthWhere['sale_month'] = 0;
                $res1 = $this->updateDataSaleMonth($coSaleMonthWhere,'year',$v);
        	} 
        }

        // 总公司，分公司年月排名
        $this->getRank('year',$timeDay);
        $this->getRank('month',$timeDay);

        if($res && $res1){
        	return 'SUCCESS';
        }else{
        	return 'FAIL';
        }
    }


    function getTimeDay()
    {
    	$return['fristDay'] = date('Y-m-01');
    	// 当月总天数
    	$return['daySum'] = date("t");
    	// 当天几号
    	$return['today'] = date("j");
    	// 年
    	$return['year'] = date("Y");
    	// 当月
    	$return['month'] = date("n");
    	return $return;
    }

    // 计算 订单信用额度
    protected function countCredit4order($co_id,$branch_id,$timeDay)
    {
    	$where['co_id'] = $co_id; 
    	$where['branch_id'] = $branch_id; 
    	$where['sale_year'] = $timeDay['year'];
    	$where['sale_month'] = $timeDay['month'];
    	
    	// 获取当月之前12月的已支付数据
		$credit4orderData = Db::name('co_sale_month')
                                ->where('id', 'not in', function ($query) use ($where) {
                                    $query->name('co_sale_month')->where($where)->field('id');
                                })
                                ->field(['paid_total'])
                                ->where(['co_id'=>$co_id,'branch_id'=>$branch_id])
                                ->order('id desc')
                                ->page('1,12')
                                ->select();

        // 判断当月之前是发有3-12个数据，小于3个数据 订单信用额度=0                        
        if(count($credit4orderData) >= 3){
        	$credit4order = array_sum(array_column($credit4orderData,'paid_total'))/count($credit4orderData);
        }else{
        	$credit4order = 0;
        }
    	return $credit4order;
    }

    protected function countCredit4admin($co_id)
    {
    	$credit4admin = Db::name('co_credit4admin')->where(['co_id'=>$co_id])->sum('point');
    	return $credit4admin;
    }

    // 公司排名
    function getRank($type,$timeDay)
    {
    	$where = '';
    	if($type  == 'year' ) $where = "where sale_year = ".$timeDay['year'];
    	if($type  == 'month' )$where = "where sale_year = ".$timeDay['year']." and sale_month = ".$timeDay['month'];
    	
    	// 总公司排序
		$co_sql = "select co_id,branch_id,sum(paid_total) as paid_totals from nt_co_sale_month ".$where." and branch_id = 0 group by co_id order by paid_totals desc";
		$co_data = Db::query($co_sql);

    	// 分公司排序
		$branch_sql = "select co_id,branch_id,sum(paid_total) as paid_totals from nt_co_sale_month ".$where." and branch_id > 0 group by branch_id order by paid_totals desc";
		$branch_data = Db::query($branch_sql);

		$newData = array_merge($co_data,$branch_data);
		if(!empty($newData)){
			// 排序
			foreach ($newData as $k => $v) {
				$paid_totals[$k] = $v['paid_totals'];
				$co_id[$k] = $v['co_id'];
				$branch_id[$k] = $v['branch_id'];
			}
			array_multisort($paid_totals, SORT_DESC, $co_id, SORT_ASC,$branch_id, SORT_ASC, $newData);

			foreach ($newData as $k1 => $v1) {
				if($type == 'year') $updateData  = ['rank'=>$k1+1];
				if($type == 'month') $updateData = ['rank_1m'=>$k1+1];
				updateData('co_sale',['co_id'=>$v1['co_id'],'branch_id'=>$v1['branch_id']],$updateData);
			}	
		}
    }

    // 获取平均付款天数
    function getPayDays($sale_id,$oldPayDay,$oldSale_qty,$saleCreate_at)
    {
    	$where['sale_id'] = $sale_id;
    	$pays = Db::name('sale_payreg')
    				->where('id', 'in', function ($query) use ($where) {
                        $query->name('sale_pay_index')->where($where)->field('sale_payreg_id');
                    })
                    ->where(['success_at'=>['gt',0]])
                    ->select();
        if(empty($pays)){
        	return 0;
        }else{
	        $time_ = '';
	        foreach ($pays as $k => $v) {
	        	$time_ += ($v['success_at'] - $saleCreate_at);
	        }         
	        // 计算当前销售当平均每个付款登记完成付款天数
	        $payDay_ = $time_/count($pays);

	        // 获取之前销售单支付总耗时
	        $oldPayDaySum = $oldPayDay*$oldSale_qty;

	        // 计算 销售单+1，平均支付天数
	        $payDay = ($oldPayDaySum + $payDay_)/($oldPayDay+1);
	        return $payDay;	
        }
        
	}

	function getsaleMonthData($where,$childWhere,$page)
	{
    	// 获取当月之前数据
		$data = Db::name('co_sale_month')
                                ->where('id', 'not in', function ($query) use ($childWhere) {
                                    $query->name('co_sale_month')->where($childWhere)->field('id');
                                })
                                ->where($where)
                                ->order('id desc')
                                ->page($page)
                                ->select();
        $return = [];                        
        foreach ($data as $k => $v) {
        	foreach ($v as $k1 => $v1) {
        		if(isset($return[$k1])){
        			$return[$k1] += $v1;
        		}else{
        			$return[$k1] = 0;
        			$return[$k1] += $v1;
        		}
        	}
        }
        return $return;
	}


    // 更新月记录表
    function updateDataSaleMonth($coSaleMonthWhere,$type,$v)
    {
        $coSaleMonthData_ = Db::name('co_sale_month')->where($coSaleMonthWhere)->find();
        $coSaleMonthData['update_at']  = time();
        $coSaleMonthData['sale_qty']   = $coSaleMonthData_ ? $coSaleMonthData_['sale_qty'] + 1 : 1;
        $coSaleMonthData['total']      = $coSaleMonthData_ ? $coSaleMonthData_['total'] + $v['pay'] :  $v['pay'];
        $coSaleMonthData['paid_total'] = $coSaleMonthData_ ? $coSaleMonthData_['paid_total'] + $v['paid'] :  $v['paid'];
        $coSaleMonthData['profit']     = $coSaleMonthData_ ? $coSaleMonthData_['profit'] + $v['profit'] :  $v['profit'];

        // 上一次数据
        $lastData = $this->lastData($coSaleMonthWhere,$type);
        // 计算成长，本次已付金额 - 上次已付金额 / 上次已付金额 保留两位小数
        if($type == 'year' && $coSaleMonthWhere['sale_month'] < 4){         // 年成长，每年前三个月不用计算，从4月开始计算年成长
            $coSaleMonthData['grow'] = 0;
        }else{
            if($lastData['paid_total'] == 0){
                $coSaleMonthData['grow'] = 100;
            }else{
                $coSaleMonthData['grow'] = round(($coSaleMonthData['paid_total']-$lastData['paid_total'])/$lastData['paid_total'],2);
            }
        }
        if(!empty($coSaleMonthData_)){
            $res1 = updateData('co_sale_month',$coSaleMonthWhere,$coSaleMonthData);
        }else{
            $coSaleMonthData['co_id'] = $coSaleMonthWhere['co_id'];
            $coSaleMonthData['branch_id'] = $coSaleMonthWhere['branch_id'];
            $coSaleMonthData['sale_year'] = $coSaleMonthWhere['sale_year'];
            $coSaleMonthData['sale_month'] = $coSaleMonthWhere['sale_month'];
            $res1 = insertData('co_sale_month',$coSaleMonthData);
        }
        if($res1 >= 0){
            return 1;
        } else{
            return 0;
        }
    }

    // 获取上一个次的数据， 计算月成长和年成长
    function lastData($data,$type)
    {
        if($type == 'month'){
            if($data['sale_month'] == 1){
                $where = ['co_id'=>$data['co_id'],'branch_id'=>$data['branch_id'],'sale_year'=>$data['sale_year']-1];
            }else{
                $where = ['co_id'=>$data['co_id'],'branch_id'=>$data['branch_id'],'sale_year'=>$data['sale_year']];
            }
            $lastMonthData = Db::name('co_sale_month')->where($where)->order('sale_month desc')->find();
        }else{
            // 年成长，每年前三个月不用计算，从4月开始计算年成长
            if($data['sale_month'] > 3){
                $where = ['co_id'=>$data['co_id'],'branch_id'=>$data['branch_id'],'sale_year'=>$data['sale_year']-1,'sale_month'=>0];
                $lastMonthData = Db::name('co_sale_month')->where($where)->find();
            }else{
                $lastMonthData = [];
            }
        }
        return $lastMonthData;
    }

}